package com.weaver.qfengx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.api.browser.service.BrowserValueInfoService;
import com.engine.common.util.ServiceUtil;
import com.engine.core.context.Context;
import com.engine.workflow.biz.RobotNode.RobotNodeBiz;
import com.engine.workflow.biz.freeNode.FreeNodeBiz;
import com.engine.workflow.biz.freeNode.RequestFreeNodeFlowBiz;
import com.engine.workflow.biz.publicApi.RequestOperateBiz;
import com.engine.workflow.cmd.publicApi.reqOperate.*;
import com.engine.workflow.cmd.workflowPath.node.overtimeSetting.ResetOvertimeCmd;
import com.engine.workflow.constant.PAResponseCode;
import com.engine.workflow.entity.freeNode.FreeNodeEntity;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import com.engine.workflow.util.CommonUtil;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.weaver.qfengx.entity.RequestBaseInfo;
import com.weaver.qfengx.entity.Result;
import com.weaver.qfengx.entity.WorkflowBaseInfo;
import com.weaver.qfengx.entity.WorkflowBillfield;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestCheckAddinRules;
import weaver.workflow.request.ComparatorUtilBean;
import weaver.workflow.request.RequestNodeFlow;
import weaver.workflow.workflow.WorkflowComInfo;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 流程相关操作工具类
 * Created by YeShengtao on 2020/8/24 15:01
 */
public class WorkflowUtils {

    private final static LogUtils log = new LogUtils(WorkflowUtils.class);


    /**
     * 查询表单信息
     */
    public static List<WorkflowBillfield> tableFieldList(String tablename) {
        if (StringUtils.isEmpty(tablename)) {
            return Lists.newArrayList();
        }
        if (tablename.contains("_dt")) { // 明细表
            return DaoUtils.querySqlToBean("select id,billid,fieldName,fieldLabel,fieldDbType," +
                            "fieldHtmlType,type,viewtype from workflow_billfield where " +
                            "detailtable  = ?)",
                    WorkflowBillfield.class, tablename);
        } else { // 主表
            return DaoUtils.querySqlToBean("select id,billid,fieldName,fieldLabel,fieldDbType," +
                            "fieldHtmlType,type,viewtype from workflow_billfield where billid " +
                            "= (select id from workflow_bill where tablename = ?) and (detailtable is null or detailtable = '')",
                    WorkflowBillfield.class, tablename);
        }
    }

    /**
     * 流程请求基本信息
     */
    public static RequestBaseInfo requestBaseInfo(String requestId) {
        RequestBaseInfo res = new RequestBaseInfo();
        Map<String, String> data = DaoUtils.executeQueryToMap("select requestid,lastnodeid,lastnodetype,status," +
                "currentnodeid,currentnodetype,requestname,creater," +
                "createdate,createtime,lastoperator,lastoperatedate,lastoperatetime,requestnamenew " +
                "from workflow_requestbase where requestid = ?", requestId);
        if (Objects.isNull(data)) {
            return null;
        }
        res.setRequestId(requestId);
        res.setLastNodeId(StringUtils.val(data.get("lastnodeid")));
        res.setLastNodeType(StringUtils.val(data.get("lastnodetype")));
        res.setStatus(StringUtils.val(data.get("status")));
        res.setCreater(StringUtils.val(data.get("creater")));
        res.setCreateDate(StringUtils.val(data.get("createdate")));
        res.setCreateTime(StringUtils.val(data.get("createtime")));
        res.setLastOperator(StringUtils.val(data.get("lastoperator")));
        res.setLastOperateDate(StringUtils.val(data.get("lastoperatedate")));
        res.setLastOperateTime(StringUtils.val(data.get("lastoperatetime")));
        res.setRequestNameNew(StringUtils.val(data.get("requestnamenew")));
        return res;
    }

    /**
     * 流程基本信息
     */
    public static WorkflowBaseInfo workflowBaseInfo(String workflowId) {
        WorkflowBaseInfo res = new WorkflowBaseInfo();
        Map<String, String> data = DaoUtils.executeQueryToMap("select id, formid, workflowname, workflowdesc, workflowtype, docPath from workflow_base where id = ?", workflowId);
        if (Objects.isNull(data)) {
            return null;
        }
        if (NumberUtils.parseInt(StringUtils.val(data.get("formid"))) < 0) {
            res.setMaintable("formtable_main_" + (-NumberUtils.parseInt(StringUtils.val(data.get("formid")))));
        }
        res.setFormId(StringUtils.val(data.get("formid")));
        res.setWorkflowId(workflowId);
        res.setDocPath(StringUtils.val(data.get("docPath")));
        res.setWorkflowName(StringUtils.val(data.get("workflowname")));
        res.setWorkflowType(StringUtils.val(data.get("workflowtype")));
        res.setWorkflowDesc(StringUtils.val(data.get("workflowdesc")));
        return res;
    }

    public static String requestIdToworkflowId(String requestId) {
        String sql = "select requestid, workflowid from workflow_requestbase where requestid = ?";
        return Objects.requireNonNull(DaoUtils.executeQueryToMap(sql, requestId)).get("workflowid");
    }

    public static String mainTable(RequestInfo requestInfo) {
        WorkflowComInfo workflowComInfo = new WorkflowComInfo();
        Util.getIntValue(workflowComInfo.getFormId("" + requestInfo.getWorkflowid()));
        return "formtable_main_" + -1 * Util.getIntValue(workflowComInfo.getFormId("" + requestInfo.getWorkflowid()));
    }

    public static String mainTableByRid(String request) {
        return DaoUtils.querySingleVal("select workflow_bill.tablename from workflow_requestbase " +
                "left join workflow_base on workflow_requestbase.workflowid = workflow_base.id " +
                "left join workflow_bill on workflow_base.formid = workflow_bill.id " +
                "where workflow_requestbase.requestid = ?", request);
    }

    public static String mainTable(String workflowId) {
        String sql = "select formid from workflow_base where id = ?";
        return "formtable_main_" + -1 * Util.getIntValue(Objects.requireNonNull(DaoUtils.executeQueryToMap(sql, workflowId)).get("formid"));
    }

    public static Map<String, String> data(String requestId, String workflowId) {
        String table = mainTable(workflowId);
        String sql = String.format("select * from %s where requestid = ?", mainTable(workflowId));
        return DaoUtils.executeQueryToMap(sql, requestId);
    }

    public static String creatorId(String requestId) {
        String sql = "select creater from workflow_requestbase where requestid = ?";
        return Objects.requireNonNull(DaoUtils.executeQueryToMap(sql, requestId)).get("creater");
    }

    public static String createNodeId(String workflowid) {
        String sql = "select a.nodeid from workflow_flownode a " +
                "left join workflow_nodebase b on b.id = a.nodeid where a.workflowid = ? " +
                "and (b.IsFreeNode is null or b.IsFreeNode!='1') and a.nodetype = 0";
        return DaoUtils.querySingleVal(sql, workflowid);
    }

    public static String requestName(String requestid) {
        return DaoUtils.querySingleVal("select requestname from workflow_requestbase where requestid = ?", requestid);
    }

    public static String prop(Property[] properties, String name) {
        for (Property property : properties) {
            if (StringUtils.equals(property.getName(), name)) {
                return Util.null2String(property.getValue());
            }
        }
        return "";
    }

    public static String currentNodeId(String requestId) {
        return DaoUtils.querySingleVal("select currentnodeid from workflow_requestbase where requestid = ?", requestId);
    }

    // 获取流程当前节点
    public static String currentNodeType(String requestid) {
        return DaoUtils.querySingleVal("select currentnodetype from workflow_requestbase where requestid = ?", requestid);
    }

    // 获取流程当前审批人员列表
    public static List<String> approverUserList(String requestid) {
        List<Map<String, String>> mapList = DaoUtils.executeQueryToMapList("select distinct w2.userid from workflow_requestbase w1, workflow_currentoperator w2 "
                + "where w1.requestid = w2.requestid and w1.currentnodeid = w2.nodeid  and w1.requestid = '" + requestid
                + "' and w2.isremark=0 and w2.preisremark=0 and w2.islasttimes=1");
        return mapList.stream().map(x -> StringUtils.valNotEmpty(x.get("userid"), "")).collect(Collectors.toList());
    }

    /**
     * 流程强制归档
     */
    public static boolean archiving(String requestid, User user) {
//        User user = User.getUser(1, 0);//系统管理员
        ReqOperateRequestEntity reqOperateRequestEntity = new ReqOperateRequestEntity();
        reqOperateRequestEntity.setRequestId(NumberUtils.parseInt(requestid, -1));//被调用的requestid
        Map<String, Object> otherparams = new HashMap<String, Object>();
        otherparams.put("ismonitor", 1);
        reqOperateRequestEntity.setOtherParams(otherparams);
//        Timer timer = new Timer();
//        timer.schedule(new HitachidoForceOverAction.Task(user, reqOperateRequestEntity), secondes * 1000);
        WorkflowRequestOperatePA workflowRequestOperatePA = (WorkflowRequestOperatePAImpl) ServiceUtil.getService(WorkflowRequestOperatePAImpl.class);
        PAResponseEntity paResponseEntity = workflowRequestOperatePA.doForceOver(user, reqOperateRequestEntity); //调用强制归档
        log.writeLog("requestid => " + requestid + ", 强制归档返回状态 ===> " + paResponseEntity.getCode());
        log.writeLog("requestid => " + requestid + ", 强制归档返回结果 ===> " + JSON.toJSONString(paResponseEntity));
        if (!StringUtils.equals("SUCCESS", paResponseEntity.getCode()))
            return false;
        return true;
    }

    public static boolean archiving(String requestid) {
        return archiving(requestid, User.getUser(1, 0));
    }

    /**
     * 更新节点前/后附加操作的数据
     * @param workflowId
     * @param ispreadd 1：节点前；0：节点后
     * @param requestid
     * @param nodeid 当前节点id
     * @param formid 表单id
     * @param user 当前用户
     * @return
     */
    public static boolean updateAddinoperate(int workflowId,String ispreadd, int requestid, int nodeid, int formid, User user) {
        boolean flag = true;
        RequestCheckAddinRules requestCheckAddinRules = new RequestCheckAddinRules();
        requestCheckAddinRules.resetParameter();
        requestCheckAddinRules.setTrack(false);
        requestCheckAddinRules.setStart(false);
        requestCheckAddinRules.setNodeid(nodeid);
        requestCheckAddinRules.setRequestid(requestid);
        requestCheckAddinRules.setWorkflowid(workflowId);
        requestCheckAddinRules.setObjid(nodeid);//猜测是作用的目标节点 那就是当前节点
        requestCheckAddinRules.setObjtype(1);
        requestCheckAddinRules.setIsbill(1);
        requestCheckAddinRules.setFormid(formid);
        requestCheckAddinRules.setIspreadd(ispreadd);
        requestCheckAddinRules.setUser(user);
        try {
            requestCheckAddinRules.checkAddinRules();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

     /**
     * 删除流程
     * @param user 用户身份
     * @param requestId 请求ID
     * @param ismonitor 是否以监控权限删除
     * @return
     */
    public static PAResponseCode delete(User user, int requestId, boolean ismonitor) {
        ReqOperateRequestEntity param = new ReqOperateRequestEntity();
        param.setRequestId(requestId);
        if (ismonitor) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("ismonitor", "1");
            param.setOtherParams(map);
        }
        DoDeleteRequestCmd doDeleteRequestCmd = new DoDeleteRequestCmd(user, param);
        PAResponseEntity execute = doDeleteRequestCmd.execute(Context.getCommandComtext());
        return execute.getCode();
    }

    /**
     * 以管理员身份删除
     * @param requestId 请求ID
     * @param ismonitor 是否以监控权限
     * @return
     */
    public static PAResponseCode delete(int requestId, boolean ismonitor) {
        return delete(User.getUser(1, 0), requestId, ismonitor);
    }

    /**
     * 删除流程, 以流程权限判断删除
     * @param requestId 请求ID
     * @return
     */
    public static PAResponseCode delete(int requestId) {
        return delete(requestId, false);
    }

    /**
     * 以指定用户删除，流程权限
     * @param user user
     * @param requestId 请求ID
     * @return
     */
    public static PAResponseCode delete(User user, int requestId) {
        return delete(user, requestId, false);
    }

    /**
     * 强制收回
     * @param user 用户身份
     * @param requestId 请求ID
     * @return
     */
    public static PAResponseCode doForceDrawBack(User user, int requestId) {
        ReqOperateRequestEntity param = new ReqOperateRequestEntity();
        param.setRequestId(requestId);
        DoForceDrawBackCmd doDeleteRequestCmd = new DoForceDrawBackCmd(user, param);
        PAResponseEntity execute = doDeleteRequestCmd.execute(Context.getCommandComtext());
        return execute.getCode();
    }

    /**
     * 退回流程
     * @param user 操作用户
     * @param requestId 请求ID
     * @param remark 签字意见
     * @param rejectToType 退回类型
     * @param rejectToNodeid 退回节点
     * @return
     */
    public static PAResponseCode rejectRequest(User user, int requestId,
                                               String remark, int rejectToType, int rejectToNodeid) {
        ReqOperateRequestEntity param = new ReqOperateRequestEntity();
        param.setRequestId(requestId);
        Map<String, Object> map = Maps.newHashMap();
        map.put("RejectToType", rejectToType);
        map.put("RejectToNodeid", rejectToNodeid);
        param.setOtherParams(map);
        param.setRemark(remark);
        DoRejectRequestCmd doRejectRequestCmd = new DoRejectRequestCmd(user, param);
        PAResponseEntity execute = doRejectRequestCmd.execute(Context.getCommandComtext());
        return execute.getCode();
    }

    /**
     * 按出口退回
     * @param user 用户
     * @param requestId  请求ID
     * @param remark 签字意见
     * @return
     */
    public static PAResponseCode rejectRequest(User user, int requestId, String remark) {
        ReqOperateRequestEntity param = new ReqOperateRequestEntity();
        param.setRequestId(requestId);
        param.setRemark(remark);
        DoRejectRequestCmd doRejectRequestCmd = new DoRejectRequestCmd(user, param);
        PAResponseEntity execute = doRejectRequestCmd.execute(Context.getCommandComtext());
        return execute.getCode();
    }

    /**
     * 按出口无签字意见退回
     * @param user 操作者
     * @param requestId 请求ID
     * @return
     */
    public static PAResponseCode rejectRequest(User user, int requestId) {
        return rejectRequest(user, requestId, null);
    }

    /**
     * 自由节点无签字意见退回
     * @param user 操作者
     * @param requestId 请求ID
     * @param rejectToType 退回类型
     * @param rejectToNodeid 节点ID
     * @return
     */
    public static PAResponseCode rejectRequest(User user, int requestId,
                                               int rejectToType, int rejectToNodeid) {
        return rejectRequest(user, requestId, null, rejectToType, rejectToNodeid);
    }

    /**
     * 自由节点无签字意见退回
     * @param user 操作者
     * @param requestId 请求ID
     * @param rejectToNodeid 节点ID
     * @return
     */
    public static PAResponseCode rejectRequest(User user, int requestId,
                                               int rejectToNodeid) {
        return rejectRequest(user, requestId, null, 0, rejectToNodeid);
    }

    /**
     * 自由节点无签字意见退回
     * @param user 操作者
     * @param remark 签字意见
     * @param rejectToNodeid 节点ID
     * @return
     */
    public static PAResponseCode rejectRequest(User user, int requestId,
                                               String remark, int rejectToNodeid) {
        return rejectRequest(user, requestId, remark, 0, rejectToNodeid);
    }

    /**
     * 转发、意见征询、转办
     * @param user 操作用户
     * @param requestId 请求ID
     * @param forwardFlag 类型 1-转发；2-意见征询；3-转办
     * @param forwardResourceIds 接收人ID串，如果是转办，接收人只能是一个人
     * @param remark 签字意见
     * @param otherParams 其他参数 {"signdocids":string,"signworkflowids":string,"annexdocids":string}
     * @return
     */
    public static PAResponseCode forwardRequest(User user, int requestId,
                                                int forwardFlag, String forwardResourceIds,
                                                String remark, Map<String, Object> otherParams) {
        ReqOperateRequestEntity param = new ReqOperateRequestEntity();
        param.setRequestId(requestId);
        param.setRemark(remark);
        if (Objects.nonNull(otherParams) && !otherParams.isEmpty()) {
            param.setOtherParams(otherParams);
        }
        param.setForwardFlag(forwardFlag);
        param.setForwardResourceIds(forwardResourceIds);
        DoForwardRequestCmd doForwardRequestCmd = new DoForwardRequestCmd(user, param);
        PAResponseEntity execute = doForwardRequestCmd.execute(Context.getCommandComtext());
        return execute.getCode();
    }

    /**
     * 转发、意见征询、转办
     * @param user 操作用户
     * @param requestId 请求ID
     * @param forwardFlag 类型 1-转发；2-意见征询；3-转办
     * @param forwardResourceIds 接收人ID串，如果是转办，接收人只能是一个人
     * @param remark 签字意见
     * @return
     */
    public static  PAResponseCode forwardRequest(User user, int requestId,
                                                 int forwardFlag, String forwardResourceIds,
                                                 String remark) {
        return forwardRequest(user, requestId, forwardFlag, forwardResourceIds, remark, null);
    }

    /**
     * 转发、意见征询、转办
     * @param user 操作用户
     * @param requestId 请求ID
     * @param forwardFlag 类型 1-转发；2-意见征询；3-转办
     * @param forwardResourceIds 接收人ID串，如果是转办，接收人只能是一个人
     * @return
     */
    public static  PAResponseCode forwardRequest(User user, int requestId,
                                                 int forwardFlag, String forwardResourceIds) {
        return forwardRequest(user, requestId, forwardFlag, forwardResourceIds, null);
    }

    /**
     * 流程撤回
     * @param user 操作用户
     * @param requestId 请求ID
     * @param remark 签字意见
     * @param isremind 是否发送提醒
     * @return
     */
    public static PAResponseCode withdrawRequest(User user, int requestId, String remark, boolean isremind) {
        ReqOperateRequestEntity param = new ReqOperateRequestEntity();
        param.setRequestId(requestId);
        param.setRemark(remark);
        // 0-不提醒；1-提醒
        param.setIsremind(isremind ? 1 : 0);
        DoWithdrawRequestCmd doWithdrawRequestCmd = new DoWithdrawRequestCmd(user, param);
        PAResponseEntity execute = doWithdrawRequestCmd.execute(Context.getCommandComtext());
        return execute.getCode();
    }

    /**
     * 流程撤回, 默认发送提醒
     * @param user 操作用户
     * @param requestId 请求ID
     * @param remark 签字意见
     * @return
     */
    public static PAResponseCode withdrawRequest(User user, int requestId, String remark) {
       return withdrawRequest(user, requestId, remark, true);
    }

    /**
     * 流程撤回, 默认发送提醒
     * @param user 操作用户
     * @param requestId 请求ID
     * @return
     */
    public static PAResponseCode withdrawRequest(User user, int requestId) {
        return withdrawRequest(user, requestId, null, true);
    }

    /**
     * 操作结果封装处理，以Result对象json返回
     * @return
     */
    public static String handleOptResult(PAResponseCode res) {
        if (res.getStatusCode() == PAResponseCode.SUCCESS.getStatusCode()) {
            return JSON.toJSONString(Result.ok());
        }
        return JSON.toJSONString(Result.fail(res.getMessage()));
    }

    /**
     * 审批节点添加处理人
     * @param requestId 请求ID
     * @param userids 处理人ids
     * @return
     */
    public static Result addDynamicOperator(int requestId, String userids) {
        return Result.ok();
    }


    public static PAResponseCode submitRequest(User user, int requestId, String remark) {
        ReqOperateRequestEntity param = new ReqOperateRequestEntity();
        param.setRequestId(requestId);
        param.setRemark(remark);
        Map<String, Object> otherParams = Maps.newHashMap();
        otherParams.put("src", "submit");
        param.setOtherParams(otherParams);
        DoSubmitRequestCmd doSubmitRequestCmd = new DoSubmitRequestCmd(user, param);
        PAResponseEntity execute = doSubmitRequestCmd.execute(Context.getCommandComtext());
        return execute.getCode();
    }

    public static PAResponseCode submitRequest(User user, int requestId) {
        return submitRequest(user, requestId, null);
    }

    /**
     * 获取流程干预节点操作人
     * @param requestid 请求ID
     * @param nodeid 目标节点ID
     * @param user 干预操作者
     * @return
     */
    public static JSONArray getMonitorWfNodeUser(int requestid, int nodeid, User user) {
        int userid = user.getUID();
        String workflowid = requestIdToworkflowId(requestid + "");
        // 获取流程创建人
        String creater = creatorId(requestid + "");
        // 根据nodeid 查询nodetype
        String nodetype = DaoUtils.querySingleVal("select nodetype from workflow_flownode where workflowid = ? and nodeid = ?", workflowid, nodeid);
        List<Object> replacedatas = Lists.newArrayList();
        if("0".equals(nodetype)){
            Map<String,Object> m1 = BrowserValueInfoService.getUserInfo(creater+"");
            replacedatas.add(m1);
        }
        String formid = DaoUtils.querySingleVal("select formid from workflow_base where id = ?", workflowid);
        String billtablename = "formtable_main_" + (-NumberUtils.parseInt(formid));
        // 获取biull
        Hashtable operatorsht = new Hashtable();
        RequestNodeFlow requestNodeFlow = new RequestNodeFlow();
        boolean NextOperator = false;
        if(FreeNodeBiz.isFreeNode(nodeid)) {
            FreeNodeEntity nodeEntity = FreeNodeBiz.getCurrentFreeNodeEntity(requestid, nodeid);
            NextOperator = RequestFreeNodeFlowBiz.getNextNodeOperators(nodeEntity,requestNodeFlow,requestid);
        } else {
            //查询节点操作者
            requestNodeFlow.setRequestid(requestid);
            requestNodeFlow.setNextnodeid(nodeid);
            requestNodeFlow.setNextnodetype(nodetype);
            requestNodeFlow.setWorkflowid(NumberUtils.parseInt(workflowid));
            requestNodeFlow.setUserid(userid);
            requestNodeFlow.setUsertype(0);
            requestNodeFlow.setCreaterid(1);
            requestNodeFlow.setCreatertype(0);
            requestNodeFlow.setIsbill(1);
            requestNodeFlow.setBillid(-NumberUtils.parseInt(formid));
            requestNodeFlow.setBilltablename(billtablename);
            requestNodeFlow.setRecordSet(new RecordSet());
            requestNodeFlow.setIsreject(0);
            requestNodeFlow.setIsintervenor("1");
            requestNodeFlow.setUser(user);
            //取的下一节点操作者
            NextOperator = requestNodeFlow.getNextOperator();
        }

        if(NextOperator){
            operatorsht = requestNodeFlow.getOperators();
            int nextnodeid=requestNodeFlow.getNextNodeid();
            List<String> userids = new ArrayList<String>();
            if(nodeid==nextnodeid){
                if(operatorsht.size() > 0){
                    TreeMap map = new TreeMap(new ComparatorUtilBean());
                    Enumeration tempKeys = operatorsht.keys();
                    while (tempKeys.hasMoreElements()) {
                        String tempKey = (String) tempKeys.nextElement();
                        ArrayList tempoperators = (ArrayList) operatorsht.get(tempKey);
                        map.put(tempKey,tempoperators);
                    }

                    Iterator iterator = map.keySet().iterator();

                    while(iterator.hasNext()) {
                        String operatorgroup = (String) iterator.next();
                        ArrayList operators = (ArrayList) operatorsht.get(operatorgroup);
                        for (int i = 0; i < operators.size(); i++) {
                            String operatorandtype = (String) operators.get(i);
                            String[] operatorandtypes = Util.TokenizerString2(operatorandtype, "_");
                            String opertor = operatorandtypes[0];
                            String opertorType = operatorandtypes[1];
                            String opertorsigntype = operatorandtypes[3];
                            String key = opertor + ":" + opertorType;
                            if(userids.contains(key) || RobotNodeBiz.operatorid.equals(opertor)){
                                continue ;
                            }else{
                                userids.add(key);
                            }
                            if(opertorsigntype.equals("-3")||opertorsigntype.equals("-4")) continue;
                            Map<String, Object> replacedata =  BrowserValueInfoService.getUserInfo(opertor);
                            if("1".equals(opertorType)){
                                replacedata = HrmUtils.getCustomerUserInfo(opertor);
                            }
                            replacedata.put("IntervenoridType",opertorsigntype);
                            replacedatas.add(replacedata);
                        }
                    }
                }
            }
        }

        return JSONArray.parseArray(JSON.toJSONString(replacedatas));
    }

    public static JSONArray getMonitorWfNodeUser(int requestid, int nodeid) {
        return getMonitorWfNodeUser(requestid, nodeid, User.getUser(1, 0));
    }

    /**
     * 获取流程干预节点操作人ID
     * @param requestid 请求ID
     * @param nodeid 目标节点ID
     * @param user 干预操作者
     * @return
     */
    public static List<Integer> getMonitorWfNodeUserIds(int requestid, int nodeid, User user) {
        JSONArray datas = getMonitorWfNodeUser(requestid, nodeid, user);
        List<Integer> res = Lists.newArrayList();
        for (int i = 0; i < datas.size(); i++) {
            res.add(datas.getJSONObject(i).getInteger("id"));
        }
        return res;
    }

    public static List<Integer> getMonitorWfNodeUserIds(int requestid, int nodeid) {
        return getMonitorWfNodeUserIds(requestid, nodeid, User.getUser(1, 0));
    }

    /**
     * 流程干预
     * @param user 干预操作者
     * @param requestId 请求ID
     * @param submitNodeId 目标节点ID
     * @param enableIntervenor 干预是否执行节点前附加操作
     * @param signType 会签类型 0 ：非会签 1：会签 2：依次逐个处理
     * @param intervenorid 干预节点接收人，多个人以","号隔开
     * @param remark 操作意见
     * @return
     */
    public static PAResponseCode doIntervenor(User user, int requestId, int submitNodeId,
                                              boolean enableIntervenor, int signType, String intervenorid,
                                              String remark) {
        ReqOperateRequestEntity param = new ReqOperateRequestEntity();
        param.setRequestId(requestId);
        param.setRemark(remark);
        param.setEnableIntervenor(enableIntervenor);
        param.setSignType(signType);
        param.setSubmitNodeId(submitNodeId);
        param.setIntervenorid(intervenorid);
        DoIntervenorCmd doIntervenorCmd = new DoIntervenorCmd(user, param);
        PAResponseEntity execute = doIntervenorCmd.execute(Context.getCommandComtext());
        return execute.getCode();
    }

    /**
     * 以系统管理员的身份进行干预
     * @param requestId 请求ID
     * @param submitNodeId 目标节点ID
     * @param enableIntervenor 干预是否执行节点前附加操作
     * @param signType 会签类型 0 ：非会签 1：会签 2：依次逐个处理
     * @param intervenorid 干预节点接收人，多个人以","号隔开
     * @param remark 操作意见
     * @return
     */
    public static PAResponseCode doIntervenor(int requestId, int submitNodeId,
                                              boolean enableIntervenor, int signType, String intervenorid,
                                              String remark) {
        return doIntervenor(User.getUser(1, 0), requestId, submitNodeId, enableIntervenor, signType, intervenorid, remark);
    }

    public static PAResponseCode doIntervenor(User user, int requestId, int submitNodeId, String intervenorid, String remark) {
        return doIntervenor(user, requestId, submitNodeId, false, 2, intervenorid, remark);
    }

    public static PAResponseCode doIntervenor(int requestId, int submitNodeId, String intervenorid, String remark) {
        return doIntervenor(requestId, submitNodeId, false, 2, intervenorid, remark);
    }

    public static PAResponseCode doIntervenor(int requestId, int submitNodeId, String intervenorid) {
        return doIntervenor(requestId, submitNodeId, false, 2, intervenorid,null);
    }

    public static PAResponseCode doIntervenorWithDefaultOperator(User user, int requestId, int submitNodeId, boolean enableIntervenor, int signType, String remark) {
        List<Integer> monitorWfNodeUserIds = getMonitorWfNodeUserIds(requestId, submitNodeId, user);
        String intervenorid = Joiner.on(",").skipNulls().join(monitorWfNodeUserIds);
        return doIntervenor(user, requestId, submitNodeId, enableIntervenor, signType, intervenorid, remark);
    }

    public static PAResponseCode doIntervenorWithDefaultOperator(User user, int requestId, int submitNodeId) {
        List<Integer> monitorWfNodeUserIds = getMonitorWfNodeUserIds(requestId, submitNodeId, user);
        String intervenorid = Joiner.on(",").skipNulls().join(monitorWfNodeUserIds);
        return doIntervenor(user, requestId, submitNodeId, false, 2, intervenorid, null);
    }

    public static PAResponseCode doIntervenorWithDefaultOperator(int requestId, int submitNodeId) {
        User user = User.getUser(1, 0);
        List<Integer> monitorWfNodeUserIds = getMonitorWfNodeUserIds(requestId, submitNodeId, user);
        String intervenorid = Joiner.on(",").skipNulls().join(monitorWfNodeUserIds);
        return doIntervenor(user, requestId, submitNodeId, false, 2, intervenorid, null);
    }

    /**
     * 刷新超时时间
     * @param workflowid
     * @param nodeid
     * @param syncnodes
     * @param isAuth
     */
    public static Map<String, Object> resetOvertime(User user, int workflowid, String syncnodes) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("workflowId", workflowid);
        params.put("syncnodes", syncnodes);
        ResetOvertimeCmd resetOvertimeCmd = new ResetOvertimeCmd(params, user);
        Map<String, Object> execute = resetOvertimeCmd.execute(Context.getCommandComtext());
        return execute;
    }

    public static Map<String, Object> resetOvertime(int workflowid, String syncnodes) {
        return resetOvertime(User.getUser(1, 0),workflowid, syncnodes);
    }
}




























